import axios from 'axios'

// 获取课程列表
export const getCourses = async () => {
  try {
    const response = await axios.get('/api/student/course/')
    return response.data
  } catch (error) {
    console.error('获取课程列表失败:', error)
    throw error
  }
}

// 获取已选课程
export const getSelectedCourses = async ({ params }) => {
  try {
    const response = await axios.get('/api/student/course-selection/', { params })
    return response.data
  } catch (error) {
    console.error('获取已选课程失败:', error)
    throw error
  }
}

// 选择课程
export const selectCourse = async (courseId, username) => {
  try {
    const response = await axios.post('/api/student/course-selection/', {
      course_id: courseId,
      username: username
    })
    return response.data
  } catch (error) {
    console.error('选择课程失败:', error)
    throw error
  }
}

// 取消选择课程
export const deselectCourse = async (courseId, username) => {
  try {
    const response = await axios.delete(`/api/student/course/${courseId}/selection/`, {
      params: { username }
    })
    return response.data
  } catch (error) {
    console.error('取消选择课程失败:', error)
    throw error
  }
}

// 创建课程学习进度记录
export const createCourseProgress = async (courseId, username) => {
  try {
    console.log(`创建课程进度记录: courseId=${courseId}, username=${username}`);

    // 确保courseId是数字
    const numericCourseId = Number(courseId);
    if (isNaN(numericCourseId)) {
      console.error(`课程ID必须是数字: ${courseId}`);
      throw new Error('课程ID无效');
    }

    // 构建请求数据
    const progressData = {
      course_id: numericCourseId,
      username: username,
      progress: 0,
      attendance_rate: 0,
      interaction_rate: 0,
      focus_rate: 0
    };

    console.log('发送进度数据:', progressData);

    const response = await axios.post('/api/student/course/progress/', progressData);
    console.log('进度创建响应:', response.data);
    return response.data;
  } catch (error) {
    console.error('创建课程进度记录失败:', error.response?.data || error.message);
    // 这里不抛出错误，因为这是一个次要操作，不应阻止主要流程
    return {
      status: 'error',
      message: error.response?.data?.message || error.message
    };
  }
}
